package com.ph.controller;

import cm.ph.shopping.facade.order.entity.PhOrderAddress;
import cm.ph.shopping.facade.order.request.PhOrderOnlineRequest;
import cm.ph.shopping.facade.order.service.IOrderService;
import cm.ph.shopping.facade.order.service.IUnLineOrerService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.entity.MemberInfo;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.permission.entity.WarehouseAddress;
import com.ph.shopping.facade.permission.service.IWarehouseAddressService;
import com.ph.shopping.facade.product.service.IProductService;
import com.ph.shopping.facade.product.vo.PhProductImageVo;
import com.ph.shopping.facade.product.vo.PhProductVo;
import com.ph.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0.0
 * @项目：phshopping
 * @描述： 商城订单页面
 * @作者： xkw
 * @创建时间： 2017/3/28
 * @Copyright by xkw
 */
@Controller
@RequestMapping("/shopping/order")
public class OrderController {

    /*日志记录器*/
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    /*线上订单接口*/
    @Reference(version = "1.0.0")
    private IOrderService iOrderService;

    /*线下订单接口*/
    @Reference(version = "1.0.0")
    private IUnLineOrerService iUnLineOrerService;

    /*会员接口*/
    @Reference(version = "1.0.0")
    private IMerchantService iMerchantService;

    /*仓库地址接口*/
    @Reference(version = "1.0.0")
    private IWarehouseAddressService iWarehouseAddressService;
    /*商品接口*/
    @Reference(version = "1.0.0")
    private IProductService iProductService;

    /**
     * 生成订单预支付页面
     *
     * @param map
     * @return String
     * @throws Exception
     * @author xkw
     */
    @RequestMapping("/generateCheckOrder")
    public String generateCheckOrder(@ModelAttribute PhOrderOnlineRequest phOrderOnlineRequest, Map<String, Object> map, HttpServletRequest request) throws Exception {
        PhProductVo productVo = new PhProductVo();
        productVo.setId(phOrderOnlineRequest.getProductId());
        //商品查询
        List<PhProductVo> phProductVoList = iProductService.getProductVoDetail(productVo);
        List<MemberInfo> memberInfoList = new ArrayList<>();
        MemberInfo member = SessionUtil.getAttribute(request);
        memberInfoList.add(member);
        map.put("memberList", memberInfoList);
        //会员id
        phOrderOnlineRequest.setMemberId(member.getId());
        //用户收货地址列表
        map.put("userAddressList", this.iOrderService.queryOrderAddress(member.getId()).getData());
        if (phProductVoList.size() > 0) {//判断该商品是否存在
            //商品类型
            map.put("productClassify", phProductVoList.get(0).getProductClassifyName());
            //商品类型
            map.put("productName", phProductVoList.get(0).getProductName());
            //供应商id
            map.put("supplierId", phProductVoList.get(0).getSupplierId());
            //商品单价
            phOrderOnlineRequest.setPrice(Double.valueOf(phProductVoList.get(0).getRetailPrice().doubleValue()));
            //邮费
            if (phProductVoList.get(0).getNumberOfPackages() == null || StringUtils.isEmpty(Integer.toString(phProductVoList.get(0).getNumberOfPackages()))) {
                phProductVoList.get(0).setNumberOfPackages(0);
            }
            if (phProductVoList.get(0).getNumberOfPackages() <= phOrderOnlineRequest.getNum()) {//包邮
                //邮费
                phOrderOnlineRequest.setPostage(0L);
                //付款金额
                phOrderOnlineRequest.setPayMoney((phProductVoList.get(0).getRetailPrice().multiply(new BigDecimal(phOrderOnlineRequest.getNum()))).doubleValue());
            } else {//不包邮
                //邮费
                phOrderOnlineRequest.setPostage(phProductVoList.get(0).getFreight().multiply(new BigDecimal(phOrderOnlineRequest.getNum())).doubleValue());
                //付款金额
                phOrderOnlineRequest.setPayMoney((phProductVoList.get(0).getRetailPrice().multiply(new BigDecimal(phOrderOnlineRequest.getNum()))).add(phProductVoList.get(0).getFreight().multiply(new BigDecimal(phOrderOnlineRequest.getNum()))).doubleValue());
            }
            //处理图片
            List<PhProductImageVo> imgList = phProductVoList.get(0).getPhProductImageVoList();
            if (imgList.size() > 0)
                map.put("productImgUrl", imgList.get(0).getUrl());
        }

        //根据商品id 查询供应商信息
        //供应商名称
        map.put("supplyerName", this.iOrderService.querySupplyerName(phOrderOnlineRequest.getProductId()).getData());

        map.put("phOrderOnlineRequest", phOrderOnlineRequest);

        return "personalCenter/personal-order-check";
    }

    /**
     * 下单接口
     *
     * @param phOrderOnlineRequest 线上订单model
     * @return String
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/addOnlineOrder", method = RequestMethod.POST)
    @ResponseBody
    public Object addOnlineOrder(@ModelAttribute PhOrderOnlineRequest phOrderOnlineRequest, HttpServletRequest request, Map<String, Object> map) throws Exception {
        return this.iOrderService.insertPhOrderOnline(phOrderOnlineRequest);
    }

    /**
     * 更新订单状态
     *
     * @param orderId 订单Id
     * @return status 1待付款，2待发货，3待收货，4已完成，5交易关闭，6退款中，7已退货
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/updateOnlineOrder", method = {RequestMethod.POST})
    @ResponseBody
    public int updateOnlineOrder(@RequestParam(value = "orderId") String orderId, @RequestParam(value = "status") Integer status, HttpServletRequest request, Map<String, Object> map) throws Exception {
        return this.iOrderService.updatePhOrderOnline(orderId, status);
    }

    /**
     * 订单详情
     *
     * @param orderId 订单Id
     * @return String
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/getOrderDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public String getOrderDetail(@RequestParam(value = "orderId", required = false) Long orderId,
                                 @RequestParam(value = "deliveryType", required = false) Integer deliveryType,
                                 HttpServletRequest request,
                                 Map<String, Object> map) throws Exception {
        String method = request.getMethod();
        if ("GET".equals(method)) {
            return "redirect:/";
        }
        List<MemberInfo> memberInfoList = new ArrayList<MemberInfo>();
        MemberInfo member = SessionUtil.getAttribute(request);
        memberInfoList.add(member);
        map.put("memberList", memberInfoList);
        Result webOnLineOrderDetail = this.iOrderService.getWebOnLineOrderDetail(orderId, deliveryType);
        logger.info(String.format("订单详情:%s", JSON.toJSONString(webOnLineOrderDetail)));
        map.put("orderDetail", webOnLineOrderDetail.getData());

        return "personalCenter/personal-order-detail";

    }

    /**
     * 查询线上订单分页
     *
     * @param status   0查全部，1待付款，3待收货，4已完成，7已退货
     * @param pageNum  当前页数
     * @param pageSize 分页条数
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/findOnlineOrders", method = {RequestMethod.GET})
    public String findOnlineOrders(
            @RequestParam(value = "status", defaultValue = "0") Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request,
            Map<String, Object> map
    )
            throws Exception {
        List<MemberInfo> memberInfoList = new ArrayList<MemberInfo>();
        MemberInfo member = SessionUtil.getAttribute(request);
        memberInfoList.add(member);
        map.put("memberList", memberInfoList);
        Result result = this.iOrderService.queryWebOnLineOrders(member.getId(), status, pageNum, pageSize);
        logger.info("订单线上列表:{}", JSON.toJSONString(result));
        map.put("orderList", result.getData());
        map.put("count", result.getCount());
        map.put("status", status);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        return "personalCenter/personal-order-online";
    }

    /**
     * 查询线下订单分页
     *
     * @param status   0查全部，1 已完成 2 已退货
     * @param pageNum  当前页数
     * @param pageSize 分页条数
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/findUnlineOrders", method = {RequestMethod.GET})
    public String findUnlineOrders(
            @RequestParam(value = "status", defaultValue = "1") Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request, Map<String, Object> map
    )
            throws Exception {
        List<MemberInfo> memberInfoList = new ArrayList<>();
        MemberInfo member = SessionUtil.getAttribute(request);
        memberInfoList.add(member);
        map.put("memberList", memberInfoList);
        status = status == 0 ? null : status;
        Result result = this.iUnLineOrerService.queryWebUnLineOrders(member.getId(), status, pageNum, pageSize);
        logger.info(String.format("订单线下列表:%s", JSON.toJSONString(result)));
        map.put("orderList", result.getData());
        map.put("count", result.getCount());
        map.put("status", status);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        return "personalCenter/personal-order-unline";
    }

    /**
     * 订单支付页面
     *
     * @param orderNo 订单号
     * @return String
     * @author xkw
     */
    @RequestMapping(value = "/orderOnlinePay", method = {RequestMethod.POST})
    public String orderOnlinePay(@RequestParam(value = "orderNo") String orderNo,
                                 @RequestParam(value = "orderId") Long orderId,
                                 @RequestParam(value = "payMoney") Double payMoney,
                                 @RequestParam(value = "deliveryType") String deliveryType,
                                 HttpServletRequest request,
                                 Map<String, Object> map) {
        List<MemberInfo> memberInfoList = new ArrayList<MemberInfo>();
        MemberInfo member = SessionUtil.getAttribute(request);
        memberInfoList.add(member);
        map.put("memberList", memberInfoList);
        map.put("orderNo", orderNo);
        map.put("orderId", orderId);
        map.put("payMoney", payMoney);
        map.put("deliveryType", deliveryType);
        return "personalCenter/personal-order-online-pay";
    }

    /**
     * 查找自提仓库地址
     *
     * @param warehouseAddress 仓库地址实体
     * @return String
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/getWarehouseAddressVoList", method = RequestMethod.POST)
    @ResponseBody
    public Object getWarehouseAddressVoList(@ModelAttribute WarehouseAddress warehouseAddress, HttpServletRequest request) throws Exception {
        //仓库地址启用
        warehouseAddress.setIsable(CommonConstants.ORDER_ADDRESS_ISABLE_YES);
        //仓库地址自提货
        warehouseAddress.setIsDeliveryPoint(CommonConstants.IS_YES_DELIVERYPOINT);
        return this.iWarehouseAddressService.getWarehouseAddressVoList(warehouseAddress);
    }

    /**
     * 新增收货地址
     *
     * @param phOrderAddress 收货地址model
     * @return String
     * @throws Exception
     * @author xkw
     */
    @RequestMapping(value = "/insertOrderAddress", method = RequestMethod.POST)
    @ResponseBody
    public Object insertOrderAddress(@ModelAttribute PhOrderAddress phOrderAddress, HttpServletRequest request) throws Exception {
        MemberInfo member = SessionUtil.getAttribute(request);
        phOrderAddress.setMemberId(member.getId());
        return this.iOrderService.insertOrderAddress(phOrderAddress);
    }
}
